package com.homedo.microservice.open.service.gateway.manager.web.autoconfig;

import com.google.common.collect.Lists;
import com.homedo.common.util.Detect;
import com.netflix.turbine.discovery.ConfigPropertyBasedDiscovery;
import com.netflix.turbine.discovery.Instance;

import java.util.Collection;
import java.util.List;

public class LocalConfigPropertyBasedDiscovery extends ConfigPropertyBasedDiscovery {
    private static final String HTTPS = "https";
    private static final String SECURE_PORT = "securePort";
    private static final String HTTP = "http";
    private static final String PORT = "port";


    @Override
    public Collection<Instance> getInstanceList() throws Exception {
        List<Instance> instances = (List<Instance>) super.getInstanceList();
        if (Detect.notEmpty(instances)) {
            instances = this.resetInstances(instances);
        }
        return instances;
    }

    private List<Instance> resetInstances(List<Instance> instances) {
        List<Instance> resetInstances = Lists.newArrayList();
        instances.forEach(e -> {
            String url = e.getHostname();
            String scheme = url.startsWith(HTTPS) ? HTTPS : HTTP;
            boolean isSecurePort = scheme.equals(HTTPS) ? true : false;
            String[] parts = url.split(":");

            Instance resetInstance = new Instance(parts[1].replace("//", ""), e.getCluster(), true);

            if (isSecurePort) {
                resetInstance.getAttributes().put(SECURE_PORT, parts[2]);
            } else {
                resetInstance.getAttributes().put(PORT, parts[2]);
            }

            resetInstances.add(resetInstance);
        });

        return resetInstances;
    }
}
